<?php

namespace app\components;

use app\helpers\SettingHelper;
use Yii;
use yii\base\ViewEvent;
use yii\web\View;

class AppController extends BaseController {

    public $layout = 'main';
    protected $modelClass;

    public $keywords;
    public $description;

    public function beforeAction($action) {
        if (!parent::beforeAction($action)) {
            return FALSE;
        }

        $theme = SettingHelper::get('web_theme', 'default');

        $viewPath = APP_ROOT . "/themes/{$theme}/views";
        Yii::$app->controller->module->setViewPath($viewPath);
        Yii::setAlias('themes', dirname(dirname($viewPath)));
        Yii::setAlias('theme', "@web/themes/{$theme}");
        Yii::setAlias('themeRoot', dirname($viewPath));

        Yii::$app->view->on(View::EVENT_BEFORE_RENDER, [$this, 'beforeRender']);
        //Yii::$app->view->on(View::EVENT_END_PAGE, [$this, 'endPage']);
        return TRUE;
    }

    public function endPage() {
        $this->view->metaTags = array_unique($this->view->metaTags);
    }

    public function beforeRender(ViewEvent $event) {
        $params = $event->params;
        if (!isset($params['content']) || $this->isAjax()) {
            return;
        }

        if (empty($this->keywords)) {
            $this->keywords = SettingHelper::get('web_keywords', '');
        }
        if (empty($this->description)) {
            $this->description = SettingHelper::get('web_description', '');
        }

        $this->view->registerMetaTag(['name' => 'description', 'content' => $this->description]);
        $this->view->registerMetaTag(['name' => 'keywords', 'content' => $this->keywords]);
    }

    public function actionError(\Exception $exception) {
        if ($exception instanceof yii\web\NotFoundHttpException) {
            $this->view->title = '404';
            return $this->renderPartial('/404');
        }
        return $this->error($exception->getMessage(), $exception->getCode() > 0 ? $exception->getCode() : 1);
    }


}